<?php
/**
 * ReportAgent.php
 * description:
 * Created by www.
 * User: SCF
 * Date: 2018/11/14 15:08
 *
 */

namespace App\Console\Commands\ReportData;

use App\Models\Agent;
use App\Models\MoneyDeposit;
use App\Models\Setting;
use App\Models\User;
use common\enum\MoneyDepositEnum;
use App\Models\ReportPartnerGame;
use function GuzzleHttp\Psr7\str;
use Illuminate\Support\Facades\DB;
use App\Models\ReportAgent as ReportAgentModel;

class ReportAgent extends BaseReport
{
    protected $signature = self::PREFIX . 'report_agent {--reload=} {--begin=} {--end=} {--command=}';

    protected $description = '代理流水统计';

    public $reportName = "ReportAgent";
    /**
     * 获取需要处理的数据
     */
    public function getData($beginTime, $endTime)
    {
        //新增人数
        $newuserlist = User::select([
            DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') as date"),
            'hall_id',
            DB::raw ("count(distinct id) as num"),
            'agent_id',
            'agent_name',
        ])->whereBetween('created_at', [$beginTime, $endTime])
            ->groupBy (['date','agent_id'])
            ->get()->toArray();
        //首存人数
        //DB::connection()->enableQueryLog();#开启执行日志
        $first_deposit = DB::table ('money_deposit as m')
            ->leftJoin ('user as u','u.id', '=', 'm.user_id')
            ->select([
            DB::raw("DATE_FORMAT(m.created_at, '%Y-%m-%d') as date"),
            'm.hall_id',
            DB::raw ("count(distinct m.user_id) as num"),
            'u.agent_id',
            'u.agent_name'
        ])->whereBetween('m.recharge_time', [$beginTime, $endTime])
            ->where(['m.status'=>MoneyDepositEnum::STATUS_PAID])
            ->where(['m.is_first'=>MoneyDepositEnum::IS_FIRST])
            ->groupBy (['date','agent_id'])
            ->get()->toArray();
        //print_r(DB::getQueryLog());   //获取查询语句、参数和执行时间
        $first_deposit = self::formatToArray ($first_deposit);
        //活跃人数
        $options = Setting::select([
            'hall_id',
            'value',
        ])->where(['key'=>"BASIC_SETTING"])
            ->get()->toArray();

        $options = json_decode($options[0]['value'],true);
        $active_player1 = DB::table('report_money_log as rml')
            ->leftJoin ('user as u','u.id', '=', 'rml.user_id')
            ->select([
            'rml.hall_id',
            'rml.user_id',
            'u.agent_id',
            'u.agent_name'
        ])->where('rml.deposit_total_amount',">=",$options['deposit_amount'])
            ->whereBetween ('rml.date',[$beginTime, $endTime])
            ->get()->toArray();

        $active_player2 = DB::table('report_partner_game as rpg')
            ->leftJoin ('user as u','u.id', '=', 'rpg.user_id')
            ->select([
            'rpg.hall_id',
            'rpg.user_id',
            'u.agent_id',
            'u.agent_name'
        ])->where('rpg.validbet',">=",$options['effective_bet_amount'])
            ->whereBetween ('rpg.date',[$beginTime, $endTime])
            ->get()->toArray();

        $active_players = array_merge (self::formatToArray ($active_player1),self::formatToArray ($active_player2));
        $active_player =  $active_player2 = [];
        foreach ($active_players as $key=>$value){
            if ($value['agent_id']==0 || is_null ($value['agent_id'])){
                continue;
            }
            $active_player[$value['hall_id']][$value['agent_id']][] = $value['user_id'];

            $active_player[$value['hall_id']][$value['agent_id']] = array_unique ($active_player[$value['hall_id']][$value['agent_id']]);
            $active_player2[$value['hall_id']][$value['agent_id']]['hall_id'] = $value['hall_id'];
            $active_player2[$value['hall_id']][$value['agent_id']]['agent_id'] = $value['agent_id'];
            $active_player2[$value['hall_id']][$value['agent_id']]['agent_name'] = $value['agent_name'];
            $active_player2[$value['hall_id']][$value['agent_id']]['active_player_count'] = count ($active_player[$value['hall_id']][$value['agent_id']]);
            $active_player2[$value['hall_id']][$value['agent_id']]['date'] = date ('Y-m-d',strtotime ($endTime));
            //$active_player2[$value['hall_id']][$value['agent_id']]['user_ids'] = implode (',',$active_player[$value['hall_id']][$value['agent_id']]);
        }

        //存款相关
        $deposit = DB::table('report_money_log as rml')
            ->leftJoin ('user as u','u.id', '=', 'rml.user_id')
            ->select([
            'rml.hall_id',
            'rml.date',
            'rml.user_id',
            'rml.deposit_online_times',
            'rml.deposit_offline_times',
            'rml.deposit_manual_times',
            'rml.deposit_total_times',
            'rml.deposit_online_amount',
            'rml.deposit_offline_amount',
            'rml.deposit_manual_amount',
            'rml.deposit_total_amount',
            'u.agent_id' ,
            'u.agent_name'
        ])->whereBetween('rml.date', [$beginTime, $endTime])
            ->get()->toArray();
        $deposit = self::formatToArray ($deposit);
        //投注相关
        $betinfos = DB::table('report_partner_game as rpg')
            ->leftJoin ('user as u','u.id', '=', 'rpg.user_id')
            ->select([
            'rpg.hall_id',
            'rpg.date',
            DB::raw ("count(distinct rpg.user_id) as num"),
            DB::raw ("sum(rpg.bet_times) as bet_times"),
            DB::raw ("sum(rpg.bet_amount) as bet_amount"),
            DB::raw ("sum(rpg.validbet) as validbet"),
            DB::raw ("sum(rpg.prize) as prize"),
            DB::raw ("sum(rpg.profit) as profit"),
            'u.agent_id' ,
            'u.agent_name'
        ])->whereBetween('rpg.date', [$beginTime, $endTime])
            ->groupBy (['rpg.date','rpg.user_id'])
            ->get()->toArray();
        $betinfos = self::formatToArray ($betinfos);
        return [
            'betinfos' =>$betinfos,
            'deposit'  => $deposit,
            'active_player' =>$active_player2,
            'first_deposit' => $first_deposit,
            'newuserlist'   => $newuserlist
        ];
    }
    /**
     * 处理数据
     */
    public function dealData($data)
    {
        $agent_data_array = [];
        foreach ($data['first_deposit'] as $first_deposit){
            if ($first_deposit['agent_id']==0 || is_null ($first_deposit['agent_id'])){
                continue;
            }
            $res = $agent_data_array[$first_deposit['hall_id']][$first_deposit['date']][$first_deposit['agent_id']]??[
                    'agent_name' => '',
                    'new_count' => 0,
                    'first_deposit_count' => 0,
                    'bet_count' => 0,
                    'active_player_count' => 0,
                    'active_player_ids' => '',
                    'deposit_online_times' => 0,
                    'deposit_offline_times' => 0,
                    'deposit_manual_times'  => 0,
                    'deposit_total_times'   => 0,
                    'deposit_online_amount' => 0,
                    'deposit_offline_amount' => 0,
                    'deposit_manual_amount' => 0,
                    'deposit_total_amount'  => 0,
                    'bet_times'             => 0,
                    'bet_amount'            => 0,
                    'validbet'              => 0,
                    'prize'                 => 0,
                    'profit'               => 0
                ];
            $res['hall_id'] = $first_deposit['hall_id'];
            $res['agent_name'] = $first_deposit['agent_name'];
            $res['agent_id'] = $first_deposit['agent_id'];
            $res['first_deposit_count'] = $first_deposit['num'];
            $res['date'] = $first_deposit['date'];
            $agent_data_array[$first_deposit['hall_id']][$first_deposit['date']][$first_deposit['agent_id']] = $res;
        }

        foreach ($data['newuserlist'] as $newuserlist){
            if ($newuserlist['agent_id']==0 || is_null ($newuserlist['agent_id'])){
                continue;
            }
            $res = $agent_data_array[$newuserlist['hall_id']][$newuserlist['date']][$newuserlist['agent_id']]??[
                    'agent_name' => '',
                    'new_count' => 0,
                    'first_deposit_count' => 0,
                    'bet_count' => 0,
                    'active_player_count' => 0,
                    'active_player_ids' => '',
                    'deposit_online_times' => 0,
                    'deposit_offline_times' => 0,
                    'deposit_manual_times'  => 0,
                    'deposit_total_times'   => 0,
                    'deposit_online_amount' => 0,
                    'deposit_offline_amount' => 0,
                    'deposit_manual_amount' => 0,
                    'deposit_total_amount'  => 0,
                    'bet_times'             => 0,
                    'bet_amount'            => 0,
                    'validbet'              => 0,
                    'prize'                 => 0,
                    'profit'               => 0
                ];
            $res['hall_id'] = $newuserlist['hall_id'];
            $res['agent_name'] = $newuserlist['agent_name'];
            $res['agent_id'] = $newuserlist['agent_id'];
            $res['new_count'] = $newuserlist['num'];
            $res['date'] = $newuserlist['date'];
            $agent_data_array[$newuserlist['hall_id']][$newuserlist['date']][$newuserlist['agent_id']] = $res;
        }
        foreach ($data['betinfos'] as $betinfo){
            if ($betinfo['agent_id']==0 || is_null ($betinfo['agent_id'])){
                continue;
            }
            $res = $agent_data_array[$betinfo['hall_id']][$betinfo['date']][$betinfo['agent_id']]??[
                    'agent_name' => '',
                    'new_count' => 0,
                    'first_deposit_count' => 0,
                    'bet_count' => 0,
                    'active_player_count' => 0,
                    'active_player_ids' => '',
                    'deposit_online_times' => 0,
                    'deposit_offline_times' => 0,
                    'deposit_manual_times'  => 0,
                    'deposit_total_times'   => 0,
                    'deposit_online_amount' => 0,
                    'deposit_offline_amount' => 0,
                    'deposit_manual_amount' => 0,
                    'deposit_total_amount'  => 0,
                    'bet_times'             => 0,
                    'bet_amount'            => 0,
                    'validbet'              => 0,
                    'prize'                 => 0,
                    'profit'               => 0
                ];
            $res['hall_id'] = $betinfo['hall_id'];
            $res['date'] =  $betinfo['date'];
            $res['agent_id'] = $betinfo['agent_id'];
            $res['agent_name'] = $betinfo['agent_name']??'';
            $res['bet_times'] += $betinfo['bet_times'];
            $res['bet_amount'] += $betinfo['bet_amount'];
            $res['validbet'] += $betinfo['validbet'];
            $res['prize'] += $betinfo['prize'];
            $res['profit'] += $betinfo['profit'];
            $res['bet_count'] += $betinfo['num'];
            $agent_data_array[$betinfo['hall_id']][$betinfo['date']][$betinfo['agent_id']] = $res;
        }
        foreach ($data['deposit'] as $deposit){
            if ($deposit['agent_id']==0 || is_null ($deposit['agent_id'])){
                continue;
            }
            $res = $agent_data_array[$deposit['hall_id']][$deposit['date']][$deposit['agent_id']]??[
                    'agent_name' => '',
                    'new_count' => 0,
                    'first_deposit_count' => 0,
                    'bet_count' => 0,
                    'active_player_count' => 0,
                    'active_player_ids' => '',
                    'deposit_online_times' => 0,
                    'deposit_offline_times' => 0,
                    'deposit_manual_times'  => 0,
                    'deposit_total_times'   => 0,
                    'deposit_online_amount' => 0,
                    'deposit_offline_amount' => 0,
                    'deposit_manual_amount' => 0,
                    'deposit_total_amount'  => 0,
                    'bet_times'             => 0,
                    'bet_amount'            => 0,
                    'validbet'              => 0,
                    'prize'                 => 0,
                    'profit'               => 0
                ];
            $res['hall_id'] = $deposit['hall_id'];
            $res['date'] =  $deposit['date'];
            $res['agent_id'] = $deposit['agent_id'];
            $res['agent_name'] = $deposit['agent_name']??'';
            $res['deposit_online_times'] += $deposit['deposit_online_times'];
            $res['deposit_offline_times'] +=  $deposit['deposit_offline_times'];
            $res['deposit_manual_times'] += $deposit['deposit_manual_times'];
            $res['deposit_total_times'] += $deposit['deposit_total_times'];
            $res['deposit_online_amount'] += $deposit['deposit_online_amount'];
            $res['deposit_offline_amount'] += $deposit['deposit_offline_amount'];
            $res['deposit_manual_amount'] += $deposit['deposit_manual_amount'];
            $res['deposit_total_amount'] += $deposit['deposit_total_amount'];
            $agent_data_array[$deposit['hall_id']][$deposit['date']][$deposit['agent_id']] = $res;
        }

        foreach ($data['active_player'] as $hid=>$active_player){
            foreach ($active_player as $aid => $player){
                $res = $agent_data_array[$hid][$player['date']][$aid]??[
                        'agent_name' => '',
                        'new_count' => 0,
                        'first_deposit_count' => 0,
                        'bet_count' => 0,
                        'active_player_count' => 0,
                        'active_player_ids' => '',
                        'deposit_online_times' => 0,
                        'deposit_offline_times' => 0,
                        'deposit_manual_times'  => 0,
                        'deposit_total_times'   => 0,
                        'deposit_online_amount' => 0,
                        'deposit_offline_amount' => 0,
                        'deposit_manual_amount' => 0,
                        'deposit_total_amount'  => 0,
                        'bet_times'             => 0,
                        'bet_amount'            => 0,
                        'validbet'              => 0,
                        'prize'                 => 0,
                        'profit'               => 0
                    ];
                $res['date'] = $player['date'];
                $res['hall_id'] = $hid;
                $res['agent_id'] = $aid;
                $res['agent_name'] = $player['agent_name'];
                $res['active_player_count'] = $player['active_player_count'];
                //$res['active_player_ids'] = $player['user_ids'];
                $agent_data_array[$hid][$player['date']][$aid] = $res;
            }
        }
        foreach ($agent_data_array as $hid => $infos) {
            foreach ($infos as $date => $agents) {
                foreach ($agents as $aid => $agent){
                    // update or insert
                    $model = ReportAgentModel::where(['hall_id' => $agent['hall_id'], 'date' => $agent['date'], 'agent_id' => $agent['agent_id']])->first();
                    if (empty($model)) {
                        $model = new ReportAgentModel($agent);
                    }else{
                        $model->update($agent);
                    }
                    if (!$model->save()) {
                        $this->error("{$this->processName} 保存数据失败: " . json_encode($model->getErrors(), JSON_UNESCAPED_UNICODE));
                        return false;
                    }
                }

            }
        }
        return true;
    }

    /*
     * 数据格式化
     */
    public static function formatToArray($std){
        return json_decode (json_encode ($std),true);
    }
}